<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="客户列表"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openDialog()">预约取号</el-button>
				<!-- <el-button type="primary" :icon="Upload" plain @click="batchAdd" v-auth="'batchAdd'">批量添加用户</el-button> -->
				<!-- <el-button type="primary" :icon="Download" plain @click="downloadFile" v-auth="'export'">导出用户数据</el-button> -->
				<!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
				<el-button v-auth="'batchAdd'" type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除用户 </el-button>
				<el-select class="selectClass" v-model="printer" placeholder="选择打印机">
					<el-option v-for="item in printerList" :key="item.name" :label="item.name" :value="item.name" />
				</el-select>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="Search" @click="openDetial(scope.row.batch_no)">预约详情</el-button>
				<el-button type="primary" link :icon="View" @click="toDetail(scope.row.batch_no)">查看订单</el-button>
				<el-button type="primary" link :icon="Printer" @click="printAll(scope.row.batch_no)">全部打印</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">废弃</el-button>
				<!-- <el-button type="primary" link :icon="Location" @click="openDialog(scope.row.id)">地址</el-button> -->
			</template>
		</ProTable>
		<!-- <UserDrawer ref="drawerRef" /> -->
		<ImportExcel ref="dialogRef" />
		<Address :type="type" v-model:showDialog="showDialog" :batchNo="batch_no" @reload="reloadList" @print="printOrder"></Address>
	</div>
</template>

<script setup lang="tsx" name="customers">
import { ref, reactive, onMounted, watch } from "vue";
import { listPrepare, printLabel } from "@/api/modules/appointment";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
// import UserDrawer from "@/views/appointment/components/UserDrawer.vue";
import Address from "@/views/appointment/components/Address.vue";
import { CirclePlus, Delete, EditPen, Printer, Search, View } from "@element-plus/icons-vue";
import { doConnect, doPrint } from "@/utils/print";
import { orderCancel, printTimes } from "@/api/modules/order";
import { ElLoading } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
// 跳转详情页
const toDetail = (batch_no: number) => {
	router.push(`/orderList/batchDetail/${batch_no}`);
};
const printer = ref("");
const printerList = ref();
const printLoading = ref();
const back = ref();
watch(back, () => {
	printTimes({ document_id: back.value.printStatus[0].documentID, type: "label" }).then(res => {});
	VPrintBack(back);
});
const VPrintBack = //打印返回
	(res: any) => {
		printLoading.value.close();

		// PrintingApi.VPrintBack({
		// 	back: res
		// }).then(res => {
		// 	this.printLoading.close();
		// 	this.getList();
		// });
	};
onMounted(() => {
	let socket = doConnect();
	socket.onmessage = function (event: any) {
		console.log(JSON.parse(event.data));
		let res = JSON.parse(event.data);
		if (res.cmd === "getPrinters") {
			printerList.value = res.printers;
		}
		if (res.cmd === "print") {
			printLoading.value = ElLoading.service({
				lock: true,
				text: "打印中...",
				background: "rgba(0, 0, 0, 0.7)"
			});
		}
		if (res.cmd === "notifyPrintResult") {
			back.value = res;
		}
		if (res.status == "failed") {
			printLoading.value.close();
			ElMessage.error(res.msg);
		}
	};
});

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	// type: 1
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	return {
		list: data.list,
		total: data.count
		// pageNum: data.pageNum,
		// pageSize: data.pageSize
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	// newParams.username && (newParams.username = "custom-" + newParams.username);
	return listPrepare(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const status = reactive([
	{
		userLabel: "启用",
		userStatus: 1
	},
	{
		userLabel: "禁用",
		userStatus: -1
	}
]);
// 表格配置项
const columns: ColumnProps[] = [
	// { type: "selection", fixed: "left", width: 80 },
	{ type: "index", label: "#", width: 80, fixed: "left" },
	// { type: "expand", label: "Expand", width: 100 },
	{
		prop: "batch_no",
		label: "批次号",
		search: { el: "input" },
		fixed: "left"
	},
	// 多级 prop
	{
		prop: "created",
		label: "创建时间",
		search: {
			el: "date-picker",
			span: 1,
			props: {
				type: "datetimerange",
				valueFormat: "YYYY-MM-DD HH:mm:ss",
				defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
			}
		}
	},
	{ prop: "num", label: "预约单数量" },
	{ prop: "operation", label: "操作", fixed: "right", width: 320 }
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	await useHandleData(orderCancel, { batch_no: params.batch_no }, `废弃批次【${params.batch_no}】`);
	proTable.value.getTableList();
};
const reloadList = () => {
	proTable.value.getTableList();
};
const showDialog = ref(false);
const batch_no = ref();
const type = ref(1);
const openDialog = (params?: number) => {
	showDialog.value = true;
	type.value = 1;
	batch_no.value = 0;
};
const openDetial = (params?: number) => {
	showDialog.value = true;
	type.value = 2;
	batch_no.value = params;
};
const printAll = (params?: number) => {
	printLabel({
		batch_no: params,
		page: 1,
		limit: 1000
	}).then((res: any) => {
		res.data.list.forEach((item: any) => {
			doPrint([item], res.data.templateURL, printer.value);
		});
	});
};
const printOrder = (params?: any) => {
	printLabel({
		batch_no: params.batch_no,
		client_id: params.client_id
	}).then((res: any) => {
		res.data.list.forEach((item: any) => {
			doPrint([item], res.data.templateURL, printer.value);
		});
	});
};
</script>
<style scoped>
.selectClass {
	position: relative;
	top: -8px;
	left: 10px;
}
</style>
